package com.zhentao.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zhentao.pojo.TcCountdownEvent;
import com.zhentao.service.TcCountdownEventService;
import com.zhentao.config.Result;
import com.zhentao.config.PageResult;
import com.zhentao.config.OperationLog;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.validation.annotation.Validated;

import javax.validation.Valid;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 倒数日事件控制器
 * 
 * @author zhentao
 */
@RestController
@RequestMapping("tea/countdown")
@Validated
public class CountdownEventController {

    @Autowired
    private TcCountdownEventService countdownEventService;

    /**
     * 获取全部倒数日事件
     */
    @GetMapping("list")
    public List<TcCountdownEvent> list() {
        return countdownEventService.list();
    }

    /**
     * 根据ID获取倒数日事件详情
     */
    @GetMapping("get/{id}")
    public TcCountdownEvent getById(@PathVariable Integer id) {
        return countdownEventService.getById(id);
    }

    /**
     * 添加倒数日事件
     */
    @PostMapping("add")
    @OperationLog(value = "添加倒数日事件", type = "添加", module = "倒数日管理")
    public Result<TcCountdownEvent> add(@Valid @RequestBody TcCountdownEvent countdownEvent) {
        try {
            countdownEvent.setCreateTime(LocalDateTime.now());
            countdownEvent.setUpdateTime(LocalDateTime.now());
            boolean success = countdownEventService.save(countdownEvent);
            
            if (success) {
                return Result.success("添加成功", countdownEvent);
            } else {
                return Result.error("添加失败");
            }
        } catch (Exception e) {
            return Result.error("添加失败：" + e.getMessage());
        }
    }

    /**
     * 更新倒数日事件
     */
    @PutMapping("update")
    @OperationLog(value = "更新倒数日事件", type = "更新", module = "倒数日管理")
    public Result<TcCountdownEvent> update(@Valid @RequestBody TcCountdownEvent countdownEvent) {
        try {
            countdownEvent.setUpdateTime(LocalDateTime.now());
            boolean success = countdownEventService.updateById(countdownEvent);
            
            if (success) {
                return Result.success("更新成功", countdownEvent);
            } else {
                return Result.error("更新失败");
            }
        } catch (Exception e) {
            return Result.error("更新失败：" + e.getMessage());
        }
    }

    /**
     * 删除倒数日事件
     */
    @DeleteMapping("delete/{id}")
    @OperationLog(value = "删除倒数日事件", type = "删除", module = "倒数日管理")
    public Result<String> delete(@PathVariable Integer id) {
        try {
            boolean success = countdownEventService.removeById(id);
            
            if (success) {
                return Result.success("删除成功");
            } else {
                return Result.error("删除失败");
            }
        } catch (Exception e) {
            return Result.error("删除失败：" + e.getMessage());
        }
    }

    /**
     * 根据创建人获取倒数日事件
     */
    @GetMapping("byCreator/{creator}")
    public Result<List<TcCountdownEvent>> getByCreator(@PathVariable String creator) {
        try {
            List<TcCountdownEvent> events = countdownEventService.getByCreator(creator);
            return Result.success("获取成功", events);
        } catch (Exception e) {
            return Result.error("获取失败：" + e.getMessage());
        }
    }

    /**
     * 获取即将到期的倒数日事件（7天内）
     */
    @GetMapping("upcoming")
    public Result<List<TcCountdownEvent>> getUpcomingEvents() {
        try {
            List<TcCountdownEvent> events = countdownEventService.getUpcomingEvents();
            return Result.success("获取成功", events);
        } catch (Exception e) {
            return Result.error("获取失败：" + e.getMessage());
        }
    }

    /**
     * 获取已过期的倒数日事件
     */
    @GetMapping("expired")
    public Result<List<TcCountdownEvent>> getExpiredEvents() {
        try {
            List<TcCountdownEvent> events = countdownEventService.getExpiredEvents();
            return Result.success("获取成功", events);
        } catch (Exception e) {
            return Result.error("获取失败：" + e.getMessage());
        }
    }

    /**
     * 分页查询倒数日事件
     */
    @GetMapping("page")
    public Result<PageResult<TcCountdownEvent>> getCountdownEventPage(
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) String keyword,
            @RequestParam(required = false) String creator) {
        try {
            Page<TcCountdownEvent> page = new Page<>(current, size);
            QueryWrapper<TcCountdownEvent> queryWrapper = new QueryWrapper<>();
            
            // 关键词搜索
            if (keyword != null && !keyword.trim().isEmpty()) {
                queryWrapper.like("event_name", keyword);
            }
            
            // 创建人筛选
            if (creator != null && !creator.trim().isEmpty()) {
                queryWrapper.eq("creator", creator);
            }
            
            queryWrapper.orderByDesc("create_time");
            
            Page<TcCountdownEvent> result = countdownEventService.page(page, queryWrapper);
            
            PageResult<TcCountdownEvent> pageResult = PageResult.of(
                (int) result.getCurrent(),
                (int) result.getSize(),
                result.getTotal(),
                result.getRecords()
            );
            
            return Result.success("分页查询成功", pageResult);
        } catch (Exception e) {
            return Result.error("分页查询失败：" + e.getMessage());
        }
    }

    /**
     * 批量删除倒数日事件
     */
    @DeleteMapping("batchDelete")
    @OperationLog(value = "批量删除倒数日事件", type = "删除", module = "倒数日管理")
    public Result<Map<String, Object>> batchDelete(@RequestBody List<Integer> ids) {
        try {
            Map<String, Object> result = new HashMap<>();
            boolean success = countdownEventService.removeByIds(ids);
            
            result.put("success", success);
            result.put("message", success ? "批量删除成功" : "批量删除失败");
            result.put("deletedCount", ids.size());
            
            return Result.success(success ? "批量删除成功" : "批量删除失败", result);
        } catch (Exception e) {
            return Result.error("批量删除失败：" + e.getMessage());
        }
    }

    /**
     * 获取倒数日统计信息
     */
    @GetMapping("statistics")
    public Result<Map<String, Object>> getCountdownStatistics() {
        try {
            Map<String, Object> statistics = new HashMap<>();
            
            // 总倒数日事件数
            long totalEvents = countdownEventService.count();
            statistics.put("totalEvents", totalEvents);
            
            // 即将到期的事件数（7天内）
            List<TcCountdownEvent> upcomingEvents = countdownEventService.getUpcomingEvents();
            statistics.put("upcomingEvents", upcomingEvents.size());
            
            // 已过期的事件数
            List<TcCountdownEvent> expiredEvents = countdownEventService.getExpiredEvents();
            statistics.put("expiredEvents", expiredEvents.size());
            
            // 今日创建的事件数
            QueryWrapper<TcCountdownEvent> todayQuery = new QueryWrapper<>();
            todayQuery.ge("create_time", LocalDateTime.now().toLocalDate().atStartOfDay());
            long todayEvents = countdownEventService.count(todayQuery);
            statistics.put("todayEvents", todayEvents);
            
            return Result.success("获取统计信息成功", statistics);
        } catch (Exception e) {
            return Result.error("获取统计信息失败：" + e.getMessage());
        }
    }

    /**
     * 搜索倒数日事件
     */
    @GetMapping("search")
    public Result<List<TcCountdownEvent>> searchCountdownEvents(@RequestParam String keyword) {
        try {
            QueryWrapper<TcCountdownEvent> queryWrapper = new QueryWrapper<>();
            queryWrapper.like("event_name", keyword);
            queryWrapper.orderByDesc("create_time");
            
            List<TcCountdownEvent> events = countdownEventService.list(queryWrapper);
            return Result.success("搜索成功", events);
        } catch (Exception e) {
            return Result.error("搜索失败：" + e.getMessage());
        }
    }
}

